<template>
    <div class="container">
        <!-- 欢迎页面 -->
        <div class="welPage" v-if="welPage">
            <!-- 倒计时 -->
            <van-circle 
                @click.native='circleClick'
                v-model="currentRate" 
                size="60px"
                :clockwise="false"
                fill='rgba(255,255,255)'
                color="#f40"
                :text="`${Math.ceil(currentRate / 50)}s`"/>
                <img src="../../images/wel01.jpg" alt="">
        </div>

        <!-- 登录页面 -->
        <div class="loginPage" v-else>
            <div class="logo">
                <img src="../../images/logo.png" alt="">
            </div>
            <div class="form">
                <van-field 
                    v-model="userInfo.phone" 
                    type="text" 
                    @blur="phoneBlur"
                    placeholder="请输入手机号"
                    left-icon="phone-o"/>
                <van-field
                    v-model="userInfo.code"
                    center
                    clearable
                    @blur="codeBlur"
                    left-icon="comment-o"
                    placeholder="请输入短信验证码">
                    <template #button>
                        <button size="small" class="sendMesage" @click="getCode">{{codeText}}</button>
                    </template>
                </van-field>
                <p class="pwdLogin" @click="loginByPwd">密码登录</p>
                <van-button 
                    @click="login"
                    size="large"
                    :disabled="!canLogin"
                    class="loginBtn"
                    type="danger">登录</van-button>
                <p class="register">
                    <span @click='register'>注册账号</span>
                    <span>忘记密码</span>
                </p>
                <div class="fastLogin">
                    <p>快捷登录</p>
                    <!-- 图标 -->
                    <van-icon name="wechat" />
                </div>
            </div>
            

        </div>
    </div>
</template>

<script>
    import { getCodeApi, loginByPhoneApi } from '../../apis/loginApis'
    //testLogin
    export default {
        data(){
            return {
                userInfo:{
                    code:'',
                    phone:'',
                },
                welPage:true,
                /**
                 * 倒计时使用数据
                 */
                currentRate: 0,
                text:'test',
                /** 
                 * 
                 */
                code:'',
                initFlag:'loading', //页面跳转判断标识
                //验证码倒计时文字
                codeText:'获取验证码',
                codeTimer:null, //获取验证码倒计时定时器，做清除定时器时使用
            }
        },
        watch:{
            /**
             * 如果用户在输入验证码之后更改手机号，清除验证码，
             * 将获取验证码按钮设置为 "获取验证码"
             * 清除倒计时定时器
             */
            'userInfo.phone'(){
                this.userInfo.code = ''

                //如果定时器依然存在，清除定时器，不存在不需要操作
                if(!!this.codeTimer) {
                    this.codeText = '获取验证码'
                    clearTimeout(this.codeTimer)
                    this.codeTimer = null
                }
            }
        },
        computed:{
            /**
             * 登录按钮能否点击
             * 号码格式正确，验证码格式正确
             */
            canLogin(){
                return ( (/^1[3-9]{1}[0-9]{9}$/.test(this.userInfo.phone)) && (/^[0-9]{4}$/.test(this.userInfo.code)))
            }
        },
        async mounted(){
            /** 倒计时 */
            this.interval = setInterval(() => {
                this.currentRate -= 1
                if (this.currentRate <= 0) {
                    clearInterval(this.interval)
                    this.interval = null //js垃圾回收机制(主线程为空才会进行垃圾回收机制，直接赋值为空可以直接进行回收)

                    this.welPage = false
                }
            }, 20)
            this.userInfo.phone = this.$route.query.phone || ''
        },
        methods:{
            /** 
             * 获取验证码
             */
            async getCode(){
                //文字不为获取验证码触发点击事件直接返回
                if(this.codeText !== '获取验证码') return
                //手机号码不符合格式提示并返回
                if(!/^1[3-9]{1}[0-9]{9}$/.test(this.userInfo.phone)){
                    this.$toast({
                        message:'请输入正确的手机号',
                        position:'bottom'
                    })
                    return
                }

                this.codeText="验证码获取中..."
                //为获取验证码，并且手机号码正确发送请求
                let result = await getCodeApi(this.userInfo.phone)
                //验证码获取失败
                if(result.code !== 200){
                    this.$toast({
                        message:'手机号码未注册或者网络错误',
                        position:'bottom'
                    })
                    this.codeText = '获取验证码'
                    return
                }
                //验证码获取成功
                this.$toast(`验证码为：${result.data.code}`)

                //验证码获取成功设置倒计时
                this.codeText = '重新获取(60s)'
                /** 
                 * 将点击的时候的时间传入倒计时函数，再在倒计时函数中获取当前时间，两者相减
                 * 每一秒更改值codeText,但是定时器不能设置为一秒一次，因为程序运行会消耗时间
                 */
                this.loopTime(Date.now())
            },
            //倒计时事件
            loopTime(_t){
                this.codeTimer = setTimeout(()=>{
                    //涉及递归，需要清除定时器
                    clearTimeout(this.codeTimer)
                    this.codeTimer = null //垃圾回收机制太慢，直接手动设置为空
                    let _pt = 60 - Math.floor((Date.now() - _t) /1000)
                    this.codeText = `重新获取(${_pt}s)`
                    if(_pt>0){
                        this.loopTime(_t)
                    }else{
                        this.codeText = '获取验证码'
                    }
                },100)
            },
            /**
             * 登录
             */
            async login(){
                let result = await loginByPhoneApi(this.userInfo)
                console.log(result);
                if (result.code !== 200) {
                    this.$toast({
                        message: '登录失败，请重试',
                        position: 'bottom'
                    })
                    return
                }
                //将后端传递回来的数据保存，包括用户信息及token
                this.$store.commit('common/mutationsUserInfo', result.data)
                console.log(this.$store);
                this.$store.commit('common/mutationsToken', result.data.token)
                this.$toast({
                    message:"登录成功",
                    position:'middle'
                })
                this.$router.push('/home') //路由跳转
            },
            /**
             * 输入框失去焦点验证格式是否正确
             */
            //手机号码输入框
            phoneBlur(){
                //号码格式不正确
                if(!(/^1[3-9]{1}[0-9]{9}$/.test(this.userInfo.phone))){
                    this.$toast({
                        message:'手机号码格式不正确',
                        position:"middle"
                    })
                }
            },
            //验证码格式输入
            codeBlur(){
                if(!(/^[0-9]{4}$/)){
                    this.$toast({
                        message:'验证码应为4位数字组合',
                        position:'middle'
                    })
                }
            },
            /**
             * 点击倒计时组件
             */
            circleClick(){
                this.welPage = false
            },
            /**
             * 点击注册通过路由跳转到注册页面
             */
            register(){
                this.$router.push('/register')
            },

            //通过密码登录
            loginByPwd(){

            }
        }
    }
</script>

<style lang="less" scoped>
    @import '../../style/common.less';
    @import '../../style/login.less';
    body{
        background: #fff
    }
    .container{
        .loginCommon();
        background: #fff;
        .welPage{
            .loginCommon();
            width: 100%;
            overflow: hidden;
            img{
                height: 100%;
                margin-left: -40px;
            }
            /** 进度条样式 */
        }
        .loginPage{
            .logo{
                display: block;
                position: relative;
                height: 200px;
                img{
                    display: block;
                    height: 100px;
                    width: 100px;
                    .loginCenter()
                }
            }
            .form{
                width: 90%;
                margin: auto;
                margin-top: 50px;

                .sendMesage{
                    background: transparent;
                    border: #fff;
                    outline: 0;
                    color: rgb(94, 179, 232);
                }
                .pwdLogin{
                    font-size: .7rem;
                    text-align: right;
                    
                }
                .register{
                    font-size: .8rem;
                    text-align: center;
                    color: rgb(160, 154, 145);
                    display: flex;
                    justify-content: center;
                    >span{
                        width: 100px;
                    }
                    >span:nth-child(1){
                        border-right: 1px solid #a09a91;
                    }
                }
                .fastLogin{
                    position: relative;
                    display: block;
                    margin-top: 100px;
                    width: 100px;
                    left: calc(50% - 50px);
                    text-align: center;
                    p{
                        font-size: .7rem;
                    }
                }
            }
        }
        
    }
    .van-circle {
        position: absolute;
        top: 10px;
        right: 10px;
    }
    /deep/ .van-field__left-icon{
        font-size: 20px;
        margin-right: 20px;
    }
    /deep/ .van-icon{
        font-size: 20px;
    }
    
    .van-icon-wechat{
        font-size: 40px;
        color: rgb(17, 188, 17);
    }

    .loginBtn{
        height: 50px;
    }
</style>